﻿using FreeSql;
using FsCms.Entity;
using FsCms.Entity.Common;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace FsCms.Service.DAL
{
    public class BaseDAL<T> where T : BaseEntity
    {
        /// <summary>
        /// 新增方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async virtual Task<long> Insert(T model)
        {
            var runsql = DataType.MySql.DB().Insert<T>(model);
            return await runsql.ExecuteIdentityAsync();
        }

        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async virtual Task<bool> Update(T model)
        {
            var runsql = DataType.MySql.DB().Update<T>().SetSource(model);
            var rows = await runsql.ExecuteAffrowsAsync();
            return rows > 0;
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async virtual Task<bool> Delete(long id)
        {
            var result = await DataType.MySql.DB().Delete<T>(id).ExecuteAffrowsAsync();
            return result > 0;
        }

        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public async virtual Task<T> GetByOne(Expression<Func<T, bool>> where)
        {
            return await DataType.MySql.DB().Select<T>()
                .Where(where).ToOneAsync();
        }

        /// <summary>
        /// 查询方法
        /// </summary>
        /// <param name="where"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public async virtual Task<(List<T> list, long count)> Query(Expression<Func<T, bool>> where,
            Expression<Func<T, T>> orderby = null, PageInfo pageInfo = null)
        {
            //设置查询条件
            var list = DataType.MySql.DB().Select<T>()
                .Where(where);

            BaseEntity baseEntity = new BaseEntity();
            //设置排序
            if (orderby != null) list = list.OrderBy(nameof(baseEntity.CreateDt) + " desc ");

            var count = list.Count();
            //设置分页操作
            if (pageInfo != null && pageInfo.IsPaging)
                list.Skip((pageInfo.PageIndex - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize);
            var resultList = await list.ToListAsync();
            //执行查询
            return (resultList, count);
        }
    }
}
